<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <title>登录页</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <!-- 自定义CSS -->
    <link th:href="@{/css/signin.css}" rel="stylesheet"/>

    <!-- 支持bootstrap tab切换 -->
    <link th:href="@{/webjars/bootstrap/5.1.3/css/bootstrap.min.css}" rel="stylesheet"/>
    <script th:src="@{/webjars/bootstrap/5.1.3/js/bootstrap.bundle.min.js}"></script>

    <!-- Jquery -->
    <script th:src="@{/webjars/jquery/3.6.0/jquery.min.js}"></script>
</head>


<body style="background: #F8F8FF">

<div class="container w-25 p-3 justify-content-center" style="background:white;">
    <h2 class="text-center p-3">统一认证中心</h2>
    <div id="liveAlertPlaceholder"></div>
    <ul class="nav nav-tabs justify-content-center" id="myTab" role="tablist">
        <li class="nav-item" role="presentation">
            <button class="nav-link active" id="home-tab" data-bs-toggle="tab" data-bs-target="#accountLogin" type="button" role="tab" aria-controls="home" aria-selected="true">账户密码登录</button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="profile-tab" data-bs-toggle="tab" data-bs-target="#phoneLogin" type="button" role="tab" aria-controls="profile" aria-selected="false">手机号登录</button>
        </li>
    </ul>
    <div class="tab-content justify-content-center" id="myTabContent">
        <div class="tab-pane fade show active" id="accountLogin" role="tabpanel" aria-labelledby="home-tab">
            <form id="accountLoginForm" class="form-signin" method="post" th:action="@{/combo/login}" onsubmit="return submitLoginForm('#accountLoginForm')">
                <input type="hidden" name="type" value="1">
                <p>
                    <input type="text" id="username" name="username" class="form-control" placeholder="用户名" required autofocus>
                </p>
                <p>
                    <input type="password" id="password" name="password" class="form-control" placeholder="密码" required>
                </p>
                <div class="d-grid gap-2">
                    <button class="btn btn-lg btn-primary btn-block" type="submit">登录</button>
                </div>
            </form>
        </div>
        <div class="tab-pane fade" id="phoneLogin" role="tabpanel" aria-labelledby="profile-tab">
            <form id="phoneLoginForm" class="form-signin" method="post" th:action="@{/combo/login}" onsubmit="return submitLoginForm('#phoneLoginForm')">
                <input type="hidden" name="type" value="2">
                <p>
                    <input type="text" id="phoneNo" name="phoneNo" class="form-control" placeholder="手机号" required autofocus>
                </p>
                <div class="input-group mb-3">
                    <input type="text" id="smsCode" name="smsCode" class="form-control" placeholder="验证码" aria-label="验证码" aria-describedby="button-send—smscode" required>
                    <button class="btn btn-outline-secondary" type="button" id="button-send-smscode" onclick="sendSmsCode()">发送验证码</button>
                </div>
                <div class="d-grid gap-2">
                    <button id="btnSubmitPhoneLogin" class="btn btn-lg btn-primary btn-block" type="submit">登录</button>
                </div>
            </form>
        </div>
    </div>
    <div class="d-flex justify-content-center" style="margin-top: 20px">
        <label>其他方式登录</label>
        <!--<a th:href="@{/oauth2/authorization/github}" style="margin-left: 10px"><img id="githubLoginIcon" alt="github登录" title="github登录" th:src="@{/img/github.png}"/></a>-->
        <a th:each="thirdLoginDto : ${thirdLoginDtoList}" th:href="@{${thirdLoginDto.loginUri}}" style="margin-left: 10px"><img th:id="${thirdLoginDto.providerId}" th:alt="${thirdLoginDto.providerId}" th:title="${thirdLoginDto.providerId}" th:src="@{${thirdLoginDto.loginIcon}}"/></a>
    </div>
</div>


<script type="text/javascript">

    /**
     * 发送验证码
     */
    function sendSmsCode() {
        /** 验证手机号非空 */
        let inputPhoneNo = document.getElementById("phoneNo");
        inputPhoneNo.setCustomValidity("");
        let inputPhoneNoValid = inputPhoneNo.checkValidity();
        console.log(inputPhoneNo.checkValidity());
        if (!inputPhoneNoValid) {
            inputPhoneNo.setCustomValidity("请输入手机号");
            //触发表单提交按钮 - 显示错误提示信息
            document.getElementById("btnSubmitPhoneLogin").click();
            return;
        }

        /** 调用获取验证码服务 */
        $.ajax({
            url: "http://oauth2-server:9000/combo/sendSmsCode",
            method: "POST",
            contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
            data: {phoneNo: inputPhoneNo.value}
        })
            .done(function(data) {
                console.log("手机验证码发送成功");
                console.log(data);
                /** 设置定时显示剩余时间 */
                let curSeconds = 0;
                //发送button
                let btnSendSmscode = document.getElementById("button-send-smscode");
                let windowSeconds = 20;
                //禁用发送button
                btnSendSmscode.disabled = true;
                //设置定时显示剩余时间
                let intervalId = setInterval(function () {
                    curSeconds++;
                    let leftSeconds = windowSeconds - curSeconds;
                    btnSendSmscode.textContent = "发送验证码(" + leftSeconds + "秒)";

                    //剩余0秒，则清除计时
                    if (leftSeconds <= 0) {
                        window.clearInterval(intervalId);
                        btnSendSmscode.disabled = false;
                        btnSendSmscode.textContent = "发送验证码";
                    }
                }, 1000);
            })
            .fail(function () {
                alert("手机验证码发送失败！", "danger");
            });
    }


    /**
     * 提交登录请求
     * @returns {boolean} 禁用自动提交（使用Ajax异步提交）
     */
    function submitLoginForm(loginFormId) {
        //提交登录请求
        $.ajax({
            url: "http://oauth2-server:9000/combo/login",
            method: "POST",
            contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
            data: $(loginFormId).serialize(),
            dataType: "json"
        })
            .done(function(respResult) {
                //登录成功则重定向到OAuth2认证端点
                if (100 == respResult.code) {
                    console.log("login success", respResult)
                    window.location.href = respResult.redirectUri;
                }
                //登录失败则弹出失败提示
                else {
                    console.log("login failure")
                    alert(respResult.msg, "danger");
                }

            })
            .fail(function () {
                //登录请求发送失败
                alert("登录请求发送失败！", "danger");
            });

        //禁用自动提交表单
        return false;
    }


    /**
     * 弹出警告
     * @param message 警告消息
     * @param type 警告类型
     */
    function alert(message, type) {
        let alertPlaceholder = document.getElementById('liveAlertPlaceholder');
        //清除原提示
        alertPlaceholder.innerHTML = "";
        //附加新提示
        let wrapper = document.createElement('div')
        wrapper.innerHTML = '<div class="alert alert-' + type + ' alert-dismissible" role="alert">' + message + '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button></div>';
        alertPlaceholder.append(wrapper);
    }

</script>
</body>
</html>
